﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;

namespace Host
{
    public class SelfStartAssemblyHost
    {
        private static SelfStartAssemblyHost self_start = new SelfStartAssemblyHost();

        public static SelfStartAssemblyHost GetInstance()
        {
            return self_start;
        }

        string[] DllNames = new string[] { ".dll" };

        /// <summary>
        /// 按项目添加Host实例
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Host> GetSelfStartHostInstance()
        {
            List<Host> hosts = new List<Host>();

            string HostPath = Path.Combine(Directory.GetCurrentDirectory());
            if (Directory.Exists(HostPath))
            {
                var files = Directory.GetFiles(HostPath);
                foreach (var item in files)
                {
                    if (!DllNames.Contains(Path.GetExtension(item).ToLower()))
                        continue;

                    Assembly item_calss = null;

                    if (File.Exists(item))
                    {
                        byte[] buffer = System.IO.File.ReadAllBytes(item);
                        item_calss = Assembly.Load(buffer);
                    }
                    else
                    {
                        item_calss = Assembly.Load(item);
                    }

                    if (item_calss == null)
                        return null;

                    //加载项目中的所有合适的类
                    foreach (var c_type in item_calss.GetTypes())
                    {
                        if (c_type.GetInterface("IHostFactory") == null)
                            continue;


                        var factory = (IHostFactory)item_calss.CreateInstance(c_type.FullName);
                        if (factory == null)
                            continue;

                        var host = factory.CreateHost();
                        if (host == null)
                            continue;

                        hosts.Add(host);
                    }
                }
            }

            return hosts;
        }
    }
}
